import { login, logout, getInfo, edit, validPassword } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  adminInfo: {
    id:0,
    admin:"",
    token:"",
    email:"",
    phone:"",
    avatar:"",
    role:"",
    introduction:""
  }
}

const mutations = {
  SET_ADMIN_INFO: (state, info) => {
    state.adminInfo = info
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  /**
   * 校验管理员密码
   * @param {*} param0
   * @param {*} userInfo
   * @returns
   */
  validPassword({ commit }, data) {
    return new Promise((resolve, reject) => {
      validPassword(data).then(resp => resolve(resp.data.data)).catch((error) => reject(error.data.data))
    })
  },

  // user edit
  edit({ commit }, userInfo) {
    return new Promise((resolve, reject)  => {
      edit(userInfo).then(resp => resolve(resp)).catch(error => reject(error))
    })
  },

  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      const { admin, password } = userInfo
      login({ admin, password }).then(resp => {
        const { msg } = resp.data
        if (msg !== "密码错误" && msg !== "管理员账号不存在" && msg !== "该账号已被锁定，请联系管理员") {
          const { token } = resp.data.data
          commit('SET_TOKEN', token)
          setToken(token)
          commit('SET_ADMIN_INFO', resp.data.data)
          localStorage.setItem('token',resp.data.data.token)
          sessionStorage.setItem('userInfo',JSON.stringify(resp.data.data))
          resolve(resp)
        }
        reject(msg)
      }).catch((error) => reject(error))
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // getInfo(state.token).then(response => {
      //   const { data } = response

        if (state.adminInfo.id === 0) state.adminInfo  = JSON.parse(sessionStorage.getItem('userInfo'))

        const data = {
          roles: ['admin'],
          introduction: state.adminInfo.introduction,
          avatar: state.adminInfo.avatar,
          name: state.adminInfo.admin
        }

        const { roles, name, avatar, introduction } = data

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
